#include "cyberrt_node.h"
#include "proto/Data.pb.h"

#include <cstring>
#include <cyber/init.h>
#include <iostream>
#include <memory>

void subscriber()
{
    apollo::cyber::Init("subscriber");
    auto data_callback = [](const std::shared_ptr<const example::demo::Data> &data) {
        std::cout << "data_callback: " << data->message() << std::endl;
    };
    auto node   = std::make_shared<CyberrtNode>("subscriber");
    auto reader = node->createReader<example::demo::Data>("/example/demo/data", data_callback);

    int ch;
    do {
        LOG(INFO) << "Press Q<Enter> to quit";
        ch = getchar();
    } while (ch != 'Q' && ch != 'q');

    std::cout << "client disconnected." << std::endl;
}

void publisher()
{
    apollo::cyber::Init("publisher");
    auto node   = std::make_shared<CyberrtNode>("publisher");
    auto writer = node->createWriter<example::demo::Data>("/example/demo/data");

    std::string message;
    int         msgId = 0;

    int ch;
    do {
        ch = getchar();
        if (ch == 'Q' || ch == 'q')
            break;

        auto data = std::make_shared<example::demo::Data>();
        data->set_id(msgId);
        message = "Hello, world: " + std::to_string(++msgId);
        data->set_message(message);

        if (writer->write(data)) {
            std::cout << "publish msg: " << message << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    } while (true);
    std::cout << "client disconnected." << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " sub/pub" << std::endl;
        return 0;
    }

    if (strcmp(argv[1], "sub") == 0) {
        subscriber();
    } else if (strcmp(argv[1], "pub") == 0) {
        publisher();
    } else {
        std::cout << "Usage: " << argv[0] << " sub/pub" << std::endl;
    }
    return 0;
}
